package com.dayu.lease.web.app.custom.converter;

import com.dayu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * 通用String2枚举类型转换器
 * @author dayu
 * @create 2024-11-13 16:39
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                T[] t = targetType.getEnumConstants();
                for (T item : t) {
                    if (item.getCode().equals(Integer.valueOf(source))){
                        return item;
                    }
                }
                throw new IllegalArgumentException("参数异常");
            }
        };
    }
}
